package leetcode_day._2022._202201._2131;

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

/**
 * @author yzh
 * @version 1.0
 * @date 2022/1/23 22:27
 * 股票价格波动
 * 算法：哈希表
 * 使用 map 来存储股票, k -- 时间戳, v -- 价格
 * 使用 treeMap 来存储最大股票价格和最小股票价格
 */
public class _23_2034 {

    class StockPrice {
        int cur;
        Map<Integer, Integer> map;
        TreeMap<Integer, Integer> treeMap;
        public StockPrice() {
            map = new HashMap<>(16);
            treeMap = new TreeMap<>();
        }

        public void update(int timestamp, int price) {
            cur = Math.max(cur, timestamp);
            if (map.containsKey(timestamp)) {
                final Integer old = map.get(timestamp);
                final Integer cnt = treeMap.get(old);
                if (cnt == 1) treeMap.remove(old);
                else treeMap.put(old, cnt - 1);
            }
            map.put(timestamp, price);
            treeMap.put(price, treeMap.getOrDefault(price, 0) + 1);
        }

        public int current() {
            return map.get(cur);
        }

        public int maximum() {
            return treeMap.lastKey();
        }

        public int minimum() {
            return treeMap.firstKey();
        }
    }

}
